package com.zjj.edu.web.controller.system;

import com.zjj.edu.common.annotation.Log;
import com.zjj.edu.common.constant.UserConstants;
import com.zjj.edu.common.core.controller.BaseController;
import com.zjj.edu.common.core.domain.AjaxResult;
import com.zjj.edu.common.core.page.TableDataInfo;
import com.zjj.edu.common.core.text.Convert;
import com.zjj.edu.common.enums.BusinessType;
import com.zjj.edu.common.utils.poi.ExcelUtil;
import com.zjj.edu.framework.util.ShiroUtils;
import com.zjj.edu.framework.util.UserPermissionUtil;
import com.zjj.edu.system.domain.SysClass;
import com.zjj.edu.system.domain.SysClassTimes;
import com.zjj.edu.system.domain.SysUser;
import com.zjj.edu.system.service.*;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 班级Controller
 *
 * @author zjj
 * @date 2020-07-09
 */
@Controller
@RequestMapping("/teach/class")
public class SysClassController extends BaseController
{
    private String prefix = "teach/class";

    @Autowired
    private ISysClassService sysClassService;

    @Autowired
    private ISysSubjectService subjectService;

    @Autowired
    private ISysSemesterService semesterService;

    @Autowired
    private ISysGradeService gradeService;

    @Autowired
    private ISysUserService userService;

    @Autowired
    private ISysClassTypeService classTypeService;

    @Autowired
    private ISysClassRoomService classRoomService;

    @Autowired
    private ISysClassTimesService classTimesService;

    @RequiresPermissions("teach:class:view")
    @GetMapping()
    public String classes(ModelMap mmap)
    {
        mmap.put("subjectList", subjectService.selectAllSysSubjectList(ShiroUtils.getTenantId()));
        mmap.put("gradeList", subjectService.selectAllSysSubjectList(ShiroUtils.getTenantId()));
        return prefix + "/class";
    }

    /**
     * 查询班级列表
     */
    @RequiresPermissions("teach:class:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(SysClass sysClass)
    {
        startPage();
        sysClass.setTenantId(ShiroUtils.getTenantId());
        List<SysClass> list = sysClassService.selectSysClassList(sysClass);
        return getDataTable(list);
    }

    /**
     * 导出班级列表
     */
    @RequiresPermissions("teach:class:export")
    @Log(title = "班级", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(SysClass sysClass)
    {
        sysClass.setTenantId(ShiroUtils.getTenantId());
        List<SysClass> list = sysClassService.selectSysClassList(sysClass);
        ExcelUtil<SysClass> util = new ExcelUtil<SysClass>(SysClass.class);
        return util.exportExcel(list, "class");
    }

    /**
     * 新增班级
     */
    @GetMapping("/add")
    public String add(ModelMap mmap)
    {
        long tenantId = ShiroUtils.getTenantId();
        mmap.put("subjectList", subjectService.selectAllSysSubjectList(tenantId));
        mmap.put("gradeList", gradeService.selectAllSysGradeList(tenantId));
        mmap.put("semesterList", semesterService.selectAllSysSemesterList(tenantId));
        mmap.put("teacherList", userService.selectAllSysUserList(tenantId));
        mmap.put("classTypeList", classTypeService.selectAllSysClassTypeList(tenantId));
        mmap.put("classRoomList", classRoomService.selectAllSysClassRoomList(tenantId));
        return prefix + "/add";
    }

    /**
     * 新增保存班级
     */
    @RequiresPermissions("teach:class:add")
    @Log(title = "班级", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(SysClass sysClass)
    {
        long tenantId = ShiroUtils.getTenantId();
        sysClass.setTenantId(tenantId);
        if (UserConstants.NAME_NOT_UNIQUE.equals(sysClassService.checkNameUnique(sysClass))) {
            return error("新增'" + sysClass.getName() + "'失败，名称已存在");
        }
        sysClass.setCreateBy(ShiroUtils.getLoginName());
        int status = sysClassService.insertSysClass(sysClass);
        if (status > 0) {
            optClassTime(sysClass, tenantId);
        }
        return toAjax(status);
    }

    /**
     *
     * @param sysClass
     * @param tenantId
     */
    private void optClassTime(SysClass sysClass, long tenantId) {
        String planClassType = sysClass.getPlanClassType();
        if ("1".equals(planClassType)) {
            return;
        }
        SysClassTimes[] classTimes = sysClass.getClassTimes();
        if (classTimes != null && classTimes.length > 0) {
            for (SysClassTimes t: classTimes) {
                t.setTenantId(tenantId);
                t.setClassId(sysClass.getId());
                t.setDelFlag("0");
                t.setCreateBy(ShiroUtils.getLoginName());
                classTimesService.insertSysClassTimes(t);
            }
        }
    }

    /**
     * 校验名称
     */
    @PostMapping("/checkNameUnique")
    @ResponseBody
    public String checkTenantNameUnique(SysClass sysClass) {
        sysClass.setTenantId(ShiroUtils.getTenantId());
        return sysClassService.checkNameUnique(sysClass);
    }

    /**
     * 修改班级
     */
    @GetMapping("/edit/{id}")
    public String edit(@PathVariable("id") Long id, ModelMap mmap)
    {
        long tenantId = ShiroUtils.getTenantId();
        mmap.put("sysClass", sysClassService.selectSysClassById(id));
        mmap.put("subjectList", subjectService.selectAllSysSubjectList(tenantId));
        mmap.put("gradeList", gradeService.selectAllSysGradeList(tenantId));
        mmap.put("semesterList", semesterService.selectAllSysSemesterList(tenantId));
        mmap.put("teacherList", userService.selectAllSysUserList(tenantId));
        mmap.put("classTypeList", classTypeService.selectAllSysClassTypeList(tenantId));
        mmap.put("classRoomList", classRoomService.selectAllSysClassRoomList(tenantId));
        return prefix + "/edit";
    }

    /**
     * 修改保存班级
     */
    @RequiresPermissions("teach:class:edit")
    @Log(title = "班级", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(SysClass sysClass)
    {
        long tenantId = ShiroUtils.getTenantId();
        sysClass.setTenantId(tenantId);
        if (UserConstants.NAME_NOT_UNIQUE.equals(sysClassService.checkNameUnique(sysClass))) {
            return error("修改班级'" + sysClass.getName() + "'失败，名称已存在");
        }
        sysClass.setUpdateBy(ShiroUtils.getLoginName());
        int status = sysClassService.updateSysClass(sysClass);
        if (status > 0) {
            classTimesService.deleteSysClassTimesByClassId(sysClass.getId(), tenantId);
            optClassTime(sysClass, tenantId);
        }
        return toAjax(status);
    }

    /**
     * 删除班级
     */
    @RequiresPermissions("teach:class:remove")
    @Log(title = "班级", businessType = BusinessType.DELETE)
    @PostMapping( "/remove")
    @ResponseBody
    public AjaxResult remove(String ids)
    {
        SysUser user = ShiroUtils.getSysUser();
        SysClass classes = new SysClass();
        classes.setIds(Convert.toStrArray(ids));
        classes.setUpdateBy(user.getUserName());
        if (!UserPermissionUtil.checkUserPermiss()) {
            classes.setTenantId(user.getTenantId());
        }
        return toAjax(sysClassService.deleteSysClassByIds(classes));
    }

    /**
     * 状态修改
     */
    @Log(title = "班级管理", businessType = BusinessType.UPDATE)
    @RequiresPermissions("teach:class:edit")
    @PostMapping("/changeStatus")
    @ResponseBody
    public AjaxResult changeStatus(SysClass sysClass)
    {
        sysClass.setTenantId(ShiroUtils.getTenantId());
        return toAjax(sysClassService.updateSysClass(sysClass));
    }

    /**
     *
     * @param mmap
     * @return
     */
    @GetMapping("/searchCourse")
    public String searchCourse(String ids, ModelMap mmap)
    {
        mmap.put("ids", ids);
        return prefix + "/searchCourse";
    }

    /**
     * 选择日期
     * @param mmap
     * @return
     */
    @GetMapping("/selectDate")
    public String selectDate(String dates, ModelMap mmap)
    {
        mmap.put("dates", dates);
        return prefix + "/selectDate";
    }


    @PostMapping("/toLoadDates")
    @ResponseBody
    public String[] toLoadDates(String dates)
    {
        String[] array = Convert.toStrArray(dates);
        return array;
    }

    @PostMapping("/loadEditDate")
    @ResponseBody
    public List<SysClassTimes> loadEditDate(long id)
    {
        long tenantId = ShiroUtils.getTenantId();
        return classTimesService.selectSysClassTimesByClassId(id, tenantId);
    }

    /**
     * 选择时段
     * @param mmap
     * @return
     */
    @GetMapping("/selectTime")
    public String selectTime(String tempDate, String time1, String time2, String time3, String time4, ModelMap mmap)
    {
        mmap.put("time1", time1);
        mmap.put("time2", time2);
        mmap.put("time3", time3);
        mmap.put("time4", time4);
        mmap.put("tempDate", tempDate);
        return prefix + "/selectTime";
    }
}
